package com.financing.wap.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.financing.wap.dto.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.financing.wap.common.BizEnums.YouDanAmountDetaiEnums;
import com.financing.wap.common.Pager;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dao.IManagerOrderDao;
import com.financing.wap.dao.IMessageDao;
import com.financing.wap.dao.IOrderDao;
import com.financing.wap.dao.IProductDao;
import com.financing.wap.dao.ISystemDao;
import com.financing.wap.dao.IUserDao;
import com.financing.wap.dao.IYouDanAmountDao;
import com.financing.wap.dao.wherecondition.WhereCondition;
import com.financing.wap.service.IOrderService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.vo.OrderCountVO;
import com.financing.wap.vo.OrderDoneCountDto;
import com.financing.wap.vo.OrderResVO;
import com.financing.wap.vo.OrderVO;
import com.financing.wap.vo.YouDanAmountVO;

/**
 * @author Mars
 * @createDate 2014年8月22日
 */
@Service("orderService")

public class OrderServiceImpl extends BaseServiceImpl implements  IOrderService{
	
	@Autowired
	private IOrderDao orderDao;
	
	@Autowired
	private IProductDao productDao;
//	
//	@Autowired
//	private IActivitiesMollionsWealthDao activitiesMollionsWealthDao;
//	
//	@Autowired
//	private IActivitieGiftDao activitieGiftDaoImpl;
//	
//	@Autowired
//	private IAccountDao accountDao;
//	
	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IManagerOrderDao managerOrderDao;
	
	@Autowired
	private ISystemDao systemDao;

	@Autowired
	private IMessageDao messageDao;
	
	@Autowired
	private IYouDanAmountDao youDanAmountDao;

	@Override
	public List<OrderDTO> getOrderList(OrderVO where) {
		List<OrderDTO> list = orderDao.getOrderList(where);
		return list;
	}

	@Override
	public Integer getOrderListCount(OrderVO where) {
		return orderDao.getOrderListCount(where);
	}
	
	@Override
	public OrderDTO getOrder(String id) {
		OrderDTO order = orderDao.getOrder(id);
		return order;
	}

	@Override
	public void changeOrderStatusPayConfirm(OrderDTO order) {
		orderDao.changeOrderStatus(order);
		OrderFlowDTO dto = new OrderFlowDTO();
		dto.setCreateBy(order.getUpdateBy());
		dto.setUpdateBy(order.getUpdateBy());
		dto.setFlowDate(new Date());
		dto.setOrderId(order.getId());
		dto.setoStatus(order.getPayStatus());
		orderDao.insertOrderFlow(dto);
	}

	@Override
	public void changeOrderStatusRebateConfirm(OrderDTO order) {
		orderDao.changeOrderStatus(order);		
		OrderFlowDTO dto = new OrderFlowDTO();
		dto.setCreateBy(order.getUpdateBy());
		dto.setUpdateBy(order.getUpdateBy());
		dto.setFlowDate(new Date());
		dto.setOrderId(order.getId());
		dto.setoStatus(order.getPayStatus());
		orderDao.insertOrderFlow(dto);
	}

	@Override
	@Transactional
	public String applyPreOrder(OrderDTO order) {
		
		String id = orderDao.applyPreOrder(order);
		OrderFlowDTO dto = new OrderFlowDTO();
		dto.setCreateBy(order.getUpdateBy());
		dto.setUpdateBy(order.getUpdateBy());
		dto.setFlowDate(new Date());
		dto.setOrderId(order.getId());
		dto.setoStatus(Constants.STATUS_PRE_NEW);
		orderDao.insertOrderFlow(dto);
		
		addManagerUser(order);
		
		// activitiesMollionsWealth(order);
		return id;
	}
	
	public void addManagerUser(OrderDTO order){
		List<String> list = orderDao.countOrderManagerForUserId(order.getFaid());
		if(list != null && list.size() == 1){
			doAddManagerUser(order, list.get(0));
		}else if(list == null || (list != null && list.size() == 0)){
			Session session = SessionUtil.getSession(false);
			UserDTO user = new UserDTO(); 
			user = session.getUser();	
			//判断是否登录使用
			if(user==null || StringUtils.isBlank(user.getLoginName())){
				UserDTO u = new UserDTO();
				u.setLoginName(order.getShopperId());
				user = userDao.queryUserLoginName(u);
			}
			
			
			if(user.getSourceCode() != null && !("").equals(user.getSourceCode()) && !("0").equals(user.getSourceCode())){
				// 查询登录用户对应的邀请人是否是订单管理员
				List<String> sysList = orderDao.queryOrderManagerUserBySource(user.getSourceCode());
				if(sysList != null && sysList.size() > 0){
					doAddManagerUser(order, sysList.get(0));
				}else{
					doAddManagerUser(order, "9253fc40-f853-11e4-aa1d-00163e0e2df9");
				}
			}else{
				doAddManagerUser(order, "9253fc40-f853-11e4-aa1d-00163e0e2df9");
			}
		}else{
			//发送短信和邮件给后台管理人员
			sendSMSandEailToWork(order,"9253fc40-f853-11e4-aa1d-00163e0e2df9");
		}
	}
	
	public void doAddManagerUser(OrderDTO order, String systemUserId) {
		// 根据产品Code查询产品信息
		List<ProductDTO> plist = productDao.getProductByPcode(order.getPid());
		ProductDTO p = null;
		if (plist != null && plist.size() > 0) {
			p = plist.get(0);
			
			// 结果小于等于1，则直接向数据库中插入订单管理人员信息
			ManagerOrderDTO mo = new ManagerOrderDTO();
			mo.setOrderId(order.getId());
			if(p.getType() != null && (Constants.pevcProjectType).equals(p.getType())){
				mo.setOrderType(Constants.pevcOrderType);//pevc   otype and ptype
			}else{
				mo.setOrderType(
						(p.getType() != null && ("02").equals(p.getType())) ? Constants.xintuoOrderType : Constants.ziguanOrderType
				);
			}
			mo.setProjectId(p.getId());
			mo.setProjectType(p.getType());
			mo.setFaUserId(order.getFaid());
			mo.setSystemUserId(systemUserId);
			mo.setCreateBy(order.getCreateBy());
			mo.setUpdateBy(order.getCreateBy());
			managerOrderDao.addManagerOrderUser(mo);
			// 历史
			ManagerOrderHistoryDTO managerOrderHistory = new ManagerOrderHistoryDTO();
			managerOrderHistory.setOrderId(mo.getOrderId());
			managerOrderHistory.setOrderType(mo.getOrderType());
			managerOrderHistory.setProjectId(mo.getProjectId());
			managerOrderHistory.setProjectType(mo.getProjectType());
			managerOrderHistory.setFaUserId(mo.getFaUserId());
			managerOrderHistory.setSystemUserIdFrom("");
			managerOrderHistory.setSystemUserIdTo(mo.getSystemUserId());
			managerOrderHistory.setCreateBy(mo.getCreateBy());
			managerOrderHistory.setCreateDate(mo.getCreateDate());
			managerOrderHistory.setUpdateBy(mo.getUpdateBy());
			managerOrderHistory.setUpdateDate(mo.getUpdateDate());
			managerOrderDao.addManagerOrderUserHistory(managerOrderHistory);// ADD
			
			//发送短信和邮件给后台管理人员
			sendSMSandEailToWork(order,systemUserId);
		}
	}
		
	private void sendSMSandEailToWork(OrderDTO order, String systemUserId ){
		Map<String,Object> adminuser = systemDao.getadminUserInfo(systemUserId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uName", order.getFaName());
		params.put("time",sdf.format(new Date()));
		params.put("orderNo", order.getId().toString());
		params.put("orderAmount", order.getAmount().divide(new BigDecimal(10000)).toString());
		params.put("productShourName", order.getpName());
		try {
			params.put("mediaSource", Constants.sourceCodeMap.get(order.getoMediaSource()));
		} catch (Exception e) {
			params.put("mediaSource","平台");
			logger.error("mediaSource error",e);
		}
		params.put("productId",order.getPid().toString());
		Map<String,Object> m  = MessageUtil.getMessage("messageAndMail","applyOrderWork",params);
		String content = (String)m.get(MessageUtil.KEY_CONTENT);
		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
		messageSmsDTO.setFpSmsContent(content);
		messageSmsDTO.setFpSmsType(Constants.orderApplySmsAd);
		messageSmsDTO.setFpSmsSendType(Constants.message_type_now);
		messageSmsDTO.setFpSmsRecivePhoneNo(adminuser.get("telephone").toString());
		
//		messageDao.addMessageSms(messageSmsDTO);  //貌似发送给产品经理
		
		MessageMailDTO messageMailDTO = new MessageMailDTO();
		messageMailDTO.setFpMailContent(content);
		messageMailDTO.setFpMailTitle("订单预约邮件通知");
		messageMailDTO.setFpMailType(Constants.mail_order_apply_per_FA);
		messageMailDTO.setFpMailSendType(Constants.message_type_now);
		messageMailDTO.setFpMailSendTimes(new Integer(0));
		messageMailDTO.setFpMailTo(adminuser.get("email").toString());
		messageMailDTO.setStatus(Constants.status_normal);
		messageMailDTO.setFpMailSendStatus(Constants.message_status_not_send);
		messageMailDTO.setCreateBy((String)params.get("uName"));
		messageMailDTO.setUpdateBy((String)params.get("uName"));
		messageMailDTO.setCreateDate(new Date());
		messageMailDTO.setUpdateDate(new Date());
		
		messageDao.insertMailInfo(messageMailDTO);
	}
	
	@Override
	public List<OrderDTO> getCorpOrderList(OrderVO where) {
		List<OrderDTO> list = orderDao.getCorpOrderList(where);
		return list;
	}

	@Override
	public Integer getCorpOrderListCount(OrderVO where) {
		return orderDao.getCorpOrderListCount(where);
	}

	@Override
	public List<OrderDTO> queryTOPOrder(Integer limit) {
		return orderDao.queryTOPOrder(limit);
	}

	@Override
	public Integer countDealOrder(String faId) {
		return orderDao.countDealOrder(faId);
	}

	@Override
	public BigDecimal getOrderAmountCount(Map<String, Object> map)
			throws Exception {
		return orderDao.getOrderAmountCount(map);
	}

	@Override
	public List<Integer> getSonFaidList(String corpId) throws Exception {
		return orderDao.getSonFaidList(corpId);
	}

	@Override
	public Integer getBiddingProjectListCount(OrderVO orderVo) {
		return orderDao.getBiddingProjectListCount(orderVo);
	}

	@Override
	public List<YouDanOrderByProjectDTO> getBiddingProjectList(OrderVO where) {
		List<YouDanOrderByProjectDTO> list = orderDao.getBiddingProjectList(where);
		return list;
	}

	@Override
	public YouDanOrderByProjectDTO getYouDanOrderByProject(Map<String, Object> tempMap) {
		YouDanOrderByProjectDTO dto = new YouDanOrderByProjectDTO();
		dto.setId((Integer) tempMap.get("pid"));
		dto.setOwnerFAId((String) tempMap.get("oOwnerId"));
		dto.setName((String) tempMap.get("pName"));
		dto.setCode((String) tempMap.get("pCode"));
		dto.setBiddingStatus((String) tempMap.get("biddingStatus"));
		// 预约中订单金额
		BigDecimal reservedAmount = orderDao.getYouDanReservedAmountByProjectId(tempMap);
		dto.setReservedAmount(this.getBigDecimalValue(reservedAmount));
		// 已打款订单金额
		BigDecimal confirmedAmount = orderDao.getYouDanConfirmedAmountByProjectId(tempMap);
		dto.setConfirmedAmount(this.getBigDecimalValue(confirmedAmount));
		// 等待佣金
		BigDecimal payingCommission = orderDao.getPayingCommission(tempMap);
		dto.setPayingCommission(this.getBigDecimalValue(payingCommission));
		// 已付佣金
		BigDecimal payedCommission = orderDao.getPayedCommission(tempMap);
		dto.setPayedCommission(this.getBigDecimalValue(payedCommission));
		return dto;
	}
	@Override
	public YouDanOrderByProjectDTO myBiddingProjectAmount(Map<String, Object> tempMap) throws SQLException {
		YouDanOrderByProjectDTO dto = new YouDanOrderByProjectDTO();
		// 查询佣金范围信息
		dto = orderDao.getYouDanCommissionByProduct(tempMap);
		// 查询保证金信息
		YouDanAmountVO youDanAmount = new YouDanAmountVO();
		youDanAmount.setFaId((String) tempMap.get("oOwnerId"));
		youDanAmount.setAssociationId(Integer.valueOf((String) tempMap.get("biddingReceiptId")));
		List<YouDanAmountDTO> youDanAmount2 = youDanAmountDao.getYouDanAmount(youDanAmount);
		if(youDanAmount2.size()>0){
			YouDanAmountDTO youDanAmountDTO = youDanAmount2.get(0);
			dto.setDepositAmount(youDanAmountDTO.getAmount());
			dto.setDepositStatus(youDanAmountDTO.getOperateType());
		}else{
			dto.setDepositAmount(new BigDecimal(0));
			dto.setDepositStatus(YouDanAmountDetaiEnums.OPERATE_TYPE_KTX);
		}
		// 查询产品信息
		ProductDTO productDTO = orderDao.getProduct(tempMap);
		dto.setOwnerFAId((String) tempMap.get("oOwnerId"));
		dto.setId(productDTO.getId());
		dto.setName(productDTO.getName());
		dto.setCode(productDTO.getCode());
		dto.setBiddingStatus((String) tempMap.get("biddingStatus"));
		dto.setType(productDTO.getType());
		// 预约中订单金额
		BigDecimal reservedAmount = orderDao.getYouDanReservedAmountByProjectId(tempMap);
		dto.setReservedAmount(this.getBigDecimalValue(reservedAmount));
		// 已打款订单金额
		BigDecimal confirmedAmount = orderDao.getYouDanConfirmedAmountByProjectId(tempMap);
		dto.setConfirmedAmount(this.getBigDecimalValue(confirmedAmount));
		// 等待佣金
		BigDecimal payingCommission = orderDao.getPayingCommission(tempMap);
		dto.setPayingCommission(this.getBigDecimalValue(payingCommission));
		// 已付佣金
		BigDecimal payedCommission = orderDao.getPayedCommission(tempMap);
		dto.setPayedCommission(this.getBigDecimalValue(payedCommission));
		return dto;
	}

	@Override
	public BigDecimal getMyYouDanOrderAllRebateAmount(OrderVO orderVo) {
		return orderDao.getMyYouDanOrderAllRebateAmount(orderVo);
	}
	private BigDecimal getBigDecimalValue(BigDecimal bigDecimal){
		if(null == bigDecimal){
			return new BigDecimal(0);
		}else{
			return bigDecimal;
		}
	}

	@Override
	public Integer getYouDanOrderListCount(OrderVO orderVo) {
		return orderDao.getYouDanOrderListCount(orderVo);
	}

	@Override
	public List<OrderDTO> getYouDanOrderList(OrderVO orderVo) {
		return orderDao.getYouDanOrderList(orderVo);
	}

	@Override
	public OrderDTO getYouDanOrderDetail(OrderVO orderVo) {
		return orderDao.getYouDanOrderDetail(orderVo);
	}

	@Override
	public OrderDTO preYouDanOrder(OrderDTO orderDto) {
		// 查看有单价
		BigDecimal common = new BigDecimal(0.01);
		HashMap<String, Object> youDanInfo = orderDao.getYouDanAmountByOrder(orderDto);
		if(null == youDanInfo){
			//非有单
			return orderDto;
		}else{
			// 计算有单返佣金额
			BigDecimal youDanPrice = (BigDecimal) youDanInfo.get("p_rebate_amount");
			orderDto.setoYouDanPrice((BigDecimal) youDanInfo.get("p_rebate_amount"));
			orderDto.setoYouDanRebate(youDanPrice.multiply(orderDto.getAmount()).multiply(common));
			orderDto.setoOwnerId(youDanInfo.get("fa_id").toString());
			orderDto.setBiddingReceiptId((Integer) youDanInfo.get("receipt_id"));
			return orderDto;
		}
	}

	@Override
	public OrderDTO getOrder(OrderVO where) {
		List<OrderDTO> list = orderDao.getOrderList(where);
		if(list != null && list.size()>0 ){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<YouDanCommissionDTO> myBiddingProjectCommission(Map<String, Object> tempMap) {
		return orderDao.myBiddingProjectCommission(tempMap);
	}

	@Override
	public void updateOrder(OrderDTO orderDto) {
		orderDao.changeOrderStatus(orderDto);
		
	}

	@Override
	public BigDecimal getMyOrderAllRebateAmount(OrderVO orderVo) {
		// 查询有单订单出单佣金总额
		BigDecimal myYouDanOrderAllRebateAmount = orderDao.getMyAllOrderRebateAmount(orderVo);
		
		return myYouDanOrderAllRebateAmount;
	}

	@Override
	public BigDecimal orderCommissionCount(String faId) {
		return orderDao.orderCommissionCount(faId);
	}
	@Override
	public BigDecimal queryOrderCostCount(FpOrderCostDTO orderCost) {
		return orderDao.queryOrderCostCount(orderCost);
	}

	@Override
	public void changeOrderStatus(OrderDTO orderDto) {
		orderDao.changeOrderStatus(orderDto);
	}

	@Override
	public List<OrderCountVO> orderListCount(OrderDTO orderDto) {

		return orderDao.orderListCount(orderDto);
	}

	@Override
	public List<OrderCountVO> orderTimesCount(OrderDTO orderDto) {
		return orderDao.orderTimesCount(orderDto);
	}
	
	@Override
	public List<OrderCountVO> orderTimesCountDone(OrderDTO orderDto) {
		return orderDao.orderTimesCountDone(orderDto);
	}
	
	@Override
	public List<OrderCountVO> orderCountByTimeAndOrg(OrderDTO orderDto, FpManagerOrder fpman) {
		return orderDao.orderCountByTimeAndOrg(orderDto, fpman);
	}
	
	@Override
	public OrderDoneCountDto queryCountOrderDone(OrderDTO orderDto, FpManagerOrder fpman, WhereCondition wc) {
		return orderDao.queryCountOrderDone(orderDto, fpman, wc);
	}
	
	@Override
	public List<OrderResVO> queryOrderDoneByWherecondition(OrderDTO orderDto, FpManagerOrder fpman, WhereCondition wc) {
		return orderDao.queryOrderDoneByWherecondition(orderDto, fpman, wc);
	}

	@Override
	public List<String> queryOrderXaxisDatas(OrderDTO order,
			FpManagerOrder fpman) {
		return orderDao.queryOrderXaxisDatas(order, fpman);
	}


}
